//
//  NSString+ACCommon.m
//  AcmedcareCore
//
//  Created by AcZx on 2018/3/9.
//

#import "NSString+ACCommon.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (ACCommon)

#pragma mark ------------> 校验相关
/**
 *  判断是否是邮箱
 */
- (BOOL)isValidEmail{
    NSString *emailRegex = @"^\\w+((\\-\\w+)|(\\.\\w+))*@[A-Za-z0-9]+((\\.|\\-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailRegex];
    return [emailTest evaluateWithObject:self];
}

/**
 *  判断是否是中文
 */
- (BOOL)isChinese{
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", match];
    
    return [predicate evaluateWithObject:self];
}

/**
 *  判断是不是url地址
 */
- (BOOL)isValidUrl{
    NSString *regex = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z0-9]{1,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#;$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^;&*+?:_/=<>]*)?)";
    NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [urlTest evaluateWithObject:self];
}

/**
 * 验证是否是手机号
 */
- (BOOL)isValidateMobile{
    NSString *regex = @"^[0-9]*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [pred evaluateWithObject:self];
}

/**
 * 验证是否是十五位身份证号
 */
- (BOOL)isValidIdentifyFifteen{
    NSString * identifyTest = @"^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
    NSPredicate*identifyPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",identifyTest];
    return [identifyPredicate evaluateWithObject:self];
}

/**
 * 验证是否是十八位身份证号
 */
- (BOOL)isValidIdentifyEighteen{
    NSString * identifyTest = @"^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
    NSPredicate*identifyPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",identifyTest];
    return [identifyPredicate evaluateWithObject:self];
}

/**
 * 验证字符串是否为空
 */
- (BOOL)isEmptyString{
    return self == nil || self.length == 0;
}

+ (BOOL)isEmpty:(NSString *)str{
    return str == nil || str.length == 0;
}

/**
 * 验证字符串长度
 */
- (NSUInteger)utf8Length{
    size_t length = strlen([self UTF8String]);
    return length;
}

/**
 * 验证两个字符串内容是否一致
 */
- (BOOL)equals:(NSString *)string{
    return [self isEqualToString:string];
}

/**
 * 验证字符串是否以指定的前缀开头
 */
- (BOOL)stringStartsWith:(NSString*)prefix{
    return [self hasPrefix:prefix];
}

/**
 * 验证字符串是否以指定的后缀结束
 */
- (BOOL)stringEndWith:(NSString*)suffix{
    return [self hasSuffix:suffix];
}

/**
 * 验证是否包含某个字符串
 */
- (BOOL)containsString:(NSString *)string {
    if (string == nil) return NO;
    return [self rangeOfString:string].location != NSNotFound;
}

/**
 * 验证是否包含表情
 */
- (BOOL)isContainsEmoji;
{
    __block BOOL returnValue = NO;
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        const unichar hs = [substring characterAtIndex:0];
        if (0xd800 <= hs && hs <= 0xdbff)
        {
            if (substring.length > 1)
            {
                const unichar ls = [substring characterAtIndex:1];
                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                if (0x1d000 <= uc && uc <= 0x1f77f)
                {
                    returnValue = YES;
                }
            }
        }
        else if (substring.length > 1)
        {
            const unichar ls = [substring characterAtIndex:1];
            if (ls == 0x20e3)
            {
                returnValue = YES;
            }
        }
        else
        {
            if (0x2100 <= hs && hs <= 0x27ff)
            {
                returnValue = YES;
            }
            else if (0x2B05 <= hs && hs <= 0x2b07)
            {
                returnValue = YES;
            }
            else if (0x2934 <= hs && hs <= 0x2935)
            {
                returnValue = YES;
            }
            else if (0x3297 <= hs && hs <= 0x3299)
            {
                returnValue = YES;
            }
            else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50)
            {
                returnValue = YES;
            }
        }
        
        *stop = returnValue;
    }];
    
    return returnValue;
}


#pragma mark ------------> 字符串处理
/**
 * 转换成小写
 */
- (NSString *)toLowerCase{
    return [self lowercaseString];
}

/**
 * 转换成大写
 */
- (NSString *)toUpperCase{
    return [self uppercaseString];
}

/**
 * 去除空格
 */
- (NSString *)noSpaceString{
    NSString *noSpaceStr = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return noSpaceStr;
}

/**
 * 递归计算符合规定的文本长度
 */
- (NSString *)cutBeyondTextInLength:(NSInteger)maxLenth
{
    size_t length = strlen([self UTF8String]);
    if (length > maxLenth)
    {
        NSString *text = [self substringToIndex:self.length - 1];
        return [text cutBeyondTextInLength:maxLenth];
    }
    else
    {
        return self;
    }
}

/**
 * 用指定分隔符将字符串分割成数组
 */
- (NSArray *)stringToArray:(NSString *)separator{
    NSArray *array = [self componentsSeparatedByString:separator];
    if ([[array objectAtIndex:0] length] > 0) {
        return array;
    }
    else{
        return  nil;
    }
}

/**
 * json字符串转字典
 */
- (id)jsonStrChangeToDictionary{
    if (self == nil) {
        return nil;
    }
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    id dic = [NSJSONSerialization JSONObjectWithData:jsonData
    options:NSJSONReadingMutableContainers error:&error];
    if(error)
    {
        return nil;
    }
    return dic;
}


/**
 * 用指定字符串替换原字符串
 */
- (NSString *)replaceAll:(NSString *)oldStr with:(NSString *)newStr{
   return [self stringByReplacingOccurrencesOfString:oldStr withString:newStr];
}

/**
 * 从指定的开始位置和结束位置开始截取字符串
 */
- (NSString *)substringFromIndex:(int)begin toIndex:(int)end{
    if (end <= begin) {
        return @"";
    }
    NSRange range = NSMakeRange(begin, end - begin);
    return [self substringWithRange:range];
}

#pragma mark ------------> 加密功能
/**
 *  md5加密(32位 常规)
 */
- (NSString *)md5{
    const char* input = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02X", result[i]];
    }
    
    return digest;
}

/**
 *  md5加密(16位)
 */
- (NSString *)md5_16{
    NSString * md5_32 = [self md5];
    NSString * result = [[md5_32 substringToIndex:24] substringFromIndex:8];
    return result;
}

/**
 *  sha1加密
 */
- (NSString *)sha1{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
    NSMutableString* result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH *2];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    return result;
}

@end
